/**
  其他境外交流项目管理
*/
<template>
  <div class="project-manage-container">
    <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
      <el-row :gutter="24" style="height: 50px;">
        <el-col :span="8">
          <el-form-item :label="$t('projectManage.projectSubCategory')">
            <el-select v-model="queryForm.condition.projectSubCategory" clearable style="width: 100%">
              <el-option
                v-for="item in options.projectSubCategory"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('projectManage.projectName')">
            <el-input v-model="queryForm.condition.projectName" :placeholder="$t('common.pla.pleaseInput')" clearable :maxlength="32" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('projectManage.enableStatus')">
            <el-select v-model="queryForm.condition.enableStatus" clearable style="width: 100%">
              <el-option
                v-for="item in options.enableStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <h1 class="condition-title">{{$t('otherOverseasExchange.otherOverseasExchangePro')}}</h1>
      <div class="edu-opertion-bar sub-title">
        <div class="float-right" style="display: flex;">
          <el-button v-if="permitToDelete" type="danger" @click="deleteChooseInfo()">{{$t('common.btn.delete')}}</el-button>
          <el-button v-if="permitToExport" type="primary" @click="exportProjectManage()">{{$t('common.btn.export')}}</el-button>
          <el-button v-if="permitToAdd" type="primary" @click="addProjectManage()">{{$t('common.btn.add')}}</el-button>
        </div>
      </div>
      <edu-table :pagination="false" :order='true' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
        <edu-table-column :label="$t('projectManage.projectName')" prop="projectName"></edu-table-column>
        <edu-table-column :label="$t('projectManage.projectSubCategory')" prop="projectSubCategoryName"></edu-table-column>
        <edu-table-column :label="$t('projectManage.studyAbroadContentName')" prop="studyAbroadContentName"></edu-table-column>
        <edu-table-column :label="$t('projectManage.createTime')" prop="createTime"></edu-table-column>
        <edu-table-column :label="$t('projectManage.enableStatus')">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.enableStatus === 1" type="success" plain>{{ scope.row.enableStatus | enableStatus }}</el-tag>
            <el-tag v-else-if="scope.row.enableStatus === 0" type="danger" plain>{{ scope.row.enableStatus | enableStatus }}</el-tag>
          </template>
        </edu-table-column>
        <edu-table-column :label="$t('projectManage.remark')" prop="remark"></edu-table-column>
        <edu-table-column :label="$t('common.text.operation')" fit width="200">
          <template slot-scope="scope">
            <el-button v-if="permitToEdit" type="text" @click="editProjectManage(scope.row)">{{$t('common.btn.edit')}}</el-button>
            <el-button v-if="permitToDelete" type="text" @click="deleteProjectManage(scope.row)">{{$t('common.btn.delete')}}</el-button>
            <el-button type="text" @click="changeProjectManage(scope.row)">
              <span v-if="scope.row.enableStatus === 1 && permitToClose">{{ $t('externamExchangeBase.deactivate') }}</span>
              <span v-else-if="scope.row.enableStatus === 0 && permitToOpen">{{ $t('externamExchangeBase.enable') }}</span>
            </el-button>
          </template>
        </edu-table-column>
      </edu-table>
      <el-row type="flex" class="row-bg" justify="end">
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryForm.pageNum_"
            :page-sizes="[20, 40, 80, 100]"
            :page-size="queryForm.pageSize_"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryForm.total_"
            style="float:right;margin-top:10px"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      :before-close="beforeClose"
      :title="title"
      width="50%"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="dialogForm" label-position="right" ref="dialogForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="$t('projectManage.projectSubCategory') + '：'"
              prop="projectSubCategory"
              :rules="[{ required: true, message: $t('projectManage.requireProjectSubCategory'), trigger: 'change' }]">
              <el-select v-model="dialogForm.projectSubCategory" :placeholder="$t('common.pla.pleaseSelect')" clearable style="width: 100%">
                <el-option
                  v-for="item in options.projectSubCategory"
                  :key="item.id"
                  :label="item.typeName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('projectManage.projectName') + '：'"
              prop="projectName"
              :rules="[{ required: true, message: $t('projectManage.requireProjectName'), trigger: 'blur'},{ validator: checkSpecial, trigger: 'blur'}]">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="dialogForm.projectName" :maxlength="32" clearable style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="$t('projectManage.studyAbroadContentName') + '：'"
              prop="studyAbroadContent"
              :rules="[{ required: true, message: $t('projectManage.requireStudyAbroadContent'), trigger: 'change'}]">
              <el-select v-model="dialogForm.studyAbroadContent" :placeholder="$t('common.pla.pleaseSelect')" clearable style="width: 100%">
                <el-option
                  v-for="item in options.studyAbroadContent"
                  :key="item.id"
                  :label="item.content"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('projectManage.remark') + '：'" prop="remark" :rules="[{ validator: checkSpecial, trigger: 'blur'}]">
              <el-input
                type="textarea"
                :rows="5"
                :maxlength="500"
                :placeholder="$t('common.pla.pleaseInput')"
                v-model="dialogForm.remark">
              </el-input>
            </el-form-item>
          </el-col >
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <template v-if="dialogMode === 'add' || dialogMode === 'edit'">
          <el-button @click="cancel('dialogForm')">{{$t('common.btn.cancel')}}</el-button>
          <el-button type="primary" @click="save('dialogForm')">{{$t('common.btn.save')}}</el-button>
        </template>
      </span>
    </el-dialog>
    <edu-export-dialog
      :disabled="exportButton"
      :title="$t('message.prompt')"
      ref="downloadRef"
      :data="exportResult">
    </edu-export-dialog>
  </div>
</template>
<script>
import externalExchangeApi from 'common/src/api/externalExchange/externalExchange';
export default {
  components: {
  },
  data () {
    return {
      auths: [],
      permitToExport: true,
      permitToAdd: true,
      permitToEdit: true,
      permitToDelete: true,
      permitToClose: true,
      permitToOpen: true,
      // permitToDeleteAll: false,
      // permitToExport: false,
      // permitToAdd: false,
      // permitToEdit: false,
      // permitToDelete: false,
      // permitToClose: false,
      // permitToOpen: false,
      title: '',
      dialogVisible: false,
      multipleSelection: [],
      baseLevel: [],
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          projectName: '',
          projectSubCategory: '',
          enableStatus: ''
        }
      },
      dialogMode: 'add',
      options: {
        // 项目子类别
        projectSubCategory: [],
        // 启用状态
        enableStatus: [
          {
            label: '全部',
            key: '0',
            value: null
          },
          {
            label: '停用',
            key: '0',
            value: 0
          },
          {
            label: '启用',
            key: '1',
            value: 1
          }
        ],
        studyAbroadContent: []
      },
      dialogForm: {
        projectSubCategory: '',
        projectName: '',
        studyAbroadContent: '',
        remark: ''
      },
      editModeInfo: {},
      dataList: [],
      exportButton: false,
      exportResult: null
    }
  },
  filters: {
    enableStatus(val) {
      switch(val) {
        case 1:
          return '启用'
        case 0:
          return '停用'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
      }
    }
    externalExchangeApi.getXMZLBOptions({
      "selectFlag": 0,
      "parentId": 2
    }).then(res => {
      if (res.code === 200 && res.data.length > 0) {
        this.options.projectSubCategory = res.data
      }
    })
    externalExchangeApi.getLXNROptions({
      id: 2
    }).then(res => {
      if (res.code === 200 && res.data.length > 0) {
        this.options.studyAbroadContent = res.data
      }
    })
    this.onSubmit()
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback();
      }
    },
    reset() {
      Object.keys(this.queryForm.condition).forEach(key => this.queryForm.condition[key] = '');
      this.onSubmit();
    },
    getListData() {
      externalExchangeApi.getProjectManageList(this.queryForm).then((res) => {
        this.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      })
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1;
      this.getListData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.getListData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getListData();
    },
    // 批量删除数据
    deleteChooseInfo() {
      if (this.multipleSelection.length > 0) {
        let deleteArray = this.multipleSelection.map(value => {
          return value.projectId
        })
        this.$delConfirm().then(_ => {
          externalExchangeApi.deleteProjectManage({
            "projectIdList": deleteArray
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: this.$t('externamExchangeBase.operateSuccessfully')
              });
              this.onSubmit();
            }
          })
        })
      } else {
        this.$message(this.$t('graduateBase.pleaseChoose'));
      }
    },
    // 导出数据
    exportProjectManage() {
      if (this.dataList.length === 0) {
        this.$message.error(this.$t('externamExchangeBase.exportNoData'))
        return
      }
      let projectIdList = []
      if (this.multipleSelection.length > 0) {
        projectIdList = this.multipleSelection.map(value => {
          return value.projectId
        })
      }
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      externalExchangeApi.getProjectManageExportKey({
        "projectIdList": projectIdList,
        "projectName": this.queryForm.condition.projectName,
        "projectSubCategory": this.queryForm.condition.projectSubCategory,
        "enableStatus": this.queryForm.condition.enableStatus
      }).then(res => {
        if (res.code === 200 && res.data) {
          let domIframe = document.createElement("iframe");
          domIframe.src = "/api/externalexchangeservice/pgOverseasExchangeProject/downloadFile?path=" + res.data
          domIframe.style.display = "none";
          document.body.appendChild(domIframe);
          this.$message.success(this.$t('externamExchangeBase.exportSuccessfully'));
        } else {
          this.$message.success(this.$t('externamExchangeBase.exportFailed'));
        }
        this.exportResult = '';
        this.exportButton = false;
        this.$refs.downloadRef.close();
      })
    },
    // 新增数据
    addProjectManage() {
      this.title = this.$t('common.btn.add')
      this.dialogMode = 'add'
      this.dialogVisible = true
    },
    // 编辑项目
    editProjectManage(row) {
      // 学生草稿状态时目录修改/删除：提示话语为：请联系学院或学校国家公派研究生项目负责人
      this.title = this.$t('common.btn.edit')
      this.dialogMode = 'edit'
      externalExchangeApi.getProjectManageDetail({
        "projectId": row.projectId
      }).then(res => {
        if (res.code === 200) {
          this.dialogForm['projectId'] = res.data.projectId
          this.dialogForm.projectSubCategory = res.data.projectSubCategoryId
          this.dialogForm.studyAbroadContent = res.data.studyAbroadContentId
          this.dialogForm.projectName = res.data.projectName
          this.dialogForm.remark = res.data.remark
          this.dialogVisible = true
        }
      })
    },
    // 删除项目
    deleteProjectManage(row) {
      this.$delConfirm().then(_ => {
        externalExchangeApi.deleteProjectManage({
          "projectIdList": [row.projectId]
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: this.$t('externamExchangeBase.operateSuccessfully')
            });
            this.onSubmit();
          }
        })
      })
    },

    // 停用/启用项目
    changeProjectManage(row) {
      externalExchangeApi.deactivateProjectManage({
        "projectId": row.projectId,
        "enableStatus": row.enableStatus === 1 ? 0 : 1
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: this.$t('externamExchangeBase.operateSuccessfully')
          });
          this.onSubmit()
        }
      })
    },
    // 保存
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogMode === 'add') {
            if (this.dialogForm.hasOwnProperty('projectId')) {
              delete this.dialogForm.projectId;
            }
            externalExchangeApi.addProjectManage(this.dialogForm).then(res => {
              this.$message({
                type: "success",
                message: this.$t('externamExchangeBase.operateSuccessfully')
              });
              this.dialogVisible = false;
              this.onSubmit();
            });
          } else if (this.dialogMode === 'edit') {
            let dialogForm = JSON.parse(JSON.stringify(this.dialogForm))
            dialogForm['id'] = dialogForm.projectId
            externalExchangeApi.editProjectManage(dialogForm).then(res => {
              this.$message({
                type: "success",
                message: this.$t('externamExchangeBase.operateSuccessfully')
              });
              this.dialogVisible = false;
              this.onSubmit();
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      this.dialogVisible = false
    },
    // 关闭x事件
    beforeClose: function (done) {
      this.dialogVisible = false;
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'internCommuni-project-manage-add') {
              this.permitToAdd = true;
            }
            if (item.authCode === 'internCommuni-project-manage-edit') {
              this.permitToEdit = true;
            }
            if (item.authCode === 'internCommuni-project-manage-delete') {
              this.permitToDelete = true;
            }
            if (item.authCode === 'internCommuni-project-manage-open') {
              this.permitToOpen = true;
            }
            if (item.authCode === 'internCommuni-project-manage-close') {
              this.permitToClose = true;
            }
            if (item.authCode === 'internCommuni-project-manage-export') {
              this.permitToExport = true;
            }
          });
        }
      },
      deep: true,
      immediate: true
    },
    dialogVisible: {
      handler(newVal) {
        if (!newVal) {
          if (this.$refs['dialogForm']) {
            this.$refs['dialogForm'].resetFields();
          }
          Object.keys(this.dialogForm).forEach(key => {
            this.$set(this.dialogForm, key, '');
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
  .condition-title {
    color: #2b3b4e;
    font-size: 18px;
    line-height: 24px;
    font-weight: bold;
  }
  .sub-title {
    margin: 16px 0;
    font-size: 16px;
    color: #000020;
    letter-spacing: 0;
  }
  .project-manage-container ::v-deep {
    .el-dialog__body {
      word-break: break-all!important;
    }
  }
</style>
